﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Core;
using Portal.Systems.Model;
using Portal.Web.Utility;
using Portal.Web.Model;
using System.Data;
using Portal.Xml.Utility;

namespace Portal.Systems.Render
{
    public class RoleMenuManagerRenderBll
    {
        static void CheckPermission(string SiteId)
        {
            try
            {
                string UserId = WebSessionUtility.GetCurrentLoginUser().UserId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, SystemPermission.StaticId, SystemPermission.funcManage, SystemPermission.funcManage, UserId, true);
            }
            catch (Exception ex)
            {
                string ReturnData = "<div class=CssAccessDenied>" + ex.Message.ToString() + " <span class=CssBack><a href=\"javascript:history.back(-1);\">Quay lại</a></span></div>\r\n";
                throw new Exception(ReturnData);
            }
        }


        static WebFolderCls[] ReadingWebFolders(string SiteId, string Folder)
        {
            SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
            string XmlFile = WebConfig.GetWebPartLayout(OSiteParam);
            DataSet ds = XmlUtility.GetDataSetFromXmlFile(XmlFile);
            DataView dv = null;
            if (string.IsNullOrEmpty(Folder))
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId=''", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            else
            {
                dv = new DataView(ds.Tables["WebFolder"], "ParentFolderId='" + Folder + "'", "SortIndex ASC", DataViewRowState.CurrentRows);
            }
            WebFolderCls[] WebFolders = WebFolderParser.ParseFromDataView(dv);
            return WebFolders;
        }

        public static bool IsChecked(string SiteId,RoleMenuCls[] RoleMenus,string WebFolderId)
        {
            for (int iIndex = 0; iIndex < RoleMenus.Length; iIndex++)
            {
                if (RoleMenus[iIndex].WebFolderId.Equals(WebFolderId))
                {
                    return true;
                }
            }
            return false;
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                CheckPermission(SiteId);
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonIconRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                string RoleId = (string)WebEnvironments.Request(SiteId, "RoleId");
                RoleCls ORole = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, RoleId);
                if (ORole == null) throw new Exception("Tham số không hợp lệ!");
                RoleMenuCls[] RoleMenus = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingRoleMenus(SiteId, RoleId);
                string Html =
                    "<script language=javascript>\r\n" +
                    "   function Save(RoleId)\r\n"+
                    "   {\r\n"+
                    "       SiteId='"+SiteId+"';\r\n"+
                    "       CheckIds=document.getElementById('txtCheckedNote').value;\r\n"+
                    "       OAjaxOut = Portal.Systems.Render.RoleMenuManagerRenderBll.ServerSideSaveCheck(SiteId,RoleId,CheckIds).value;\r\n" +
                    "       if(OAjaxOut.Error)\r\n"+
                    "       {\r\n"+
                    "           alert(OAjaxOut.InfoMessage);\r\n"+
                    "           return;\r\n"+
                    "       }\r\n"+
                    "       alert(OAjaxOut.InfoMessage);\r\n" +
                    "   }\r\n"+
                    "</script>\r\n" +
                    " <input type=hidden style=\"width:600px;\" type=textbox id=\"txtCheckedNote\"/>\r\n"+
                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:Save('"+RoleId+"');\"><img class=image src=\"" + ButtonIconRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                    "            <li onclick=\"javascript:window.open('RoleMan.aspx','_self');\"><img class=image src=\"" + ButtonIconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    " </div>\r\n" +
                    "<h3>Vị trí công việc - "+ORole.RoleName+"</h3>\r\n"+
                    "<div class=TreeHolder>\r\n" +
                    "<div id=\"tree\">\r\n" +
                    "<ul>\r\n" +
                    " <li class=\"folder expanded\"><a href=\"#\" target=\"_self\">Màn hình gốc</a>\r\n" +
                    "     <ul>\r\n";
                WebFolderCls[] WebFolders = ReadingWebFolders(SiteId, null);
                for (int iIndex = 0; iIndex < WebFolders.Length; iIndex++)
                {
                    string AppendClass = "";
                    if (IsChecked(SiteId, RoleMenus, WebFolders[iIndex].Id))
                    {
                        AppendClass = " selected ";
                    }
                    Html +=
                            "<li id=\"" + WebFolders[iIndex].Id + "\" class=\"folder expanded " + AppendClass + "\"><a  href=\"" + WebFolders[iIndex].Id + "\" target=\"_self\">" + WebFolders[iIndex].Title + "</a>\r\n" +
                                BuildSubTreeView(SiteId, WebFolders[iIndex].Id, RoleMenus).HtmlContent +
                            "</li>\r\n";
                }

                Html += "</ul>\r\n" +
                        "</li>\r\n" +
                        "</ul>\r\n" +
                        "</div>\r\n" +
                        "</div>\r\n";


                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut BuildSubTreeView(
            string SiteId, 
            string ParentWebFolderId,
            RoleMenuCls[] RoleMenus)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string Html = "";
                WebFolderCls[] WebFolders = ReadingWebFolders(SiteId, ParentWebFolderId);
                Html +=
                    "<ul>\r\n";
                for (int iIndex = 0; iIndex < WebFolders.Length; iIndex++)
                {
                    string AppendClass = "";
                    if (IsChecked(SiteId, RoleMenus, WebFolders[iIndex].Id))
                    {
                        AppendClass = " selected ";
                    }
                    Html +=
                            "<li id=\"" + WebFolders[iIndex].Id + "\" class=\"folder expanded " + AppendClass + "\"><a  target=\"_self\" href=\"" + WebFolders[iIndex].Id + "\">" + WebFolders[iIndex].Title + "</a>\r\n" +
                                BuildSubTreeView(SiteId, WebFolders[iIndex].Id, RoleMenus).HtmlContent +
                            "</li>\r\n";
                }

                Html += "</ul>\r\n";
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
        
        [AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
        public static AjaxOut ServerSideSaveCheck(string SiteId, string RoleId, string CheckIds)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam=WebEnvironments.CreateSiteParam(SiteId);
                string AssetCode = WebSessionUtility.GetCurrentLoginUser().AssetCode;
                CheckIds=CheckIds.Replace("_","");
                string[] Ids = CheckIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                RoleMenuCls[] RoleMenus = new RoleMenuCls[Ids.Length];
                for (int iIndex = 0; iIndex < RoleMenus.Length; iIndex++)
                {
                    RoleMenus[iIndex] = new RoleMenuCls();
                    RoleMenus[iIndex].AssetCode = AssetCode;
                    RoleMenus[iIndex].Allow = 1;
                    RoleMenus[iIndex].frkRoleId = RoleId;
                    RoleMenus[iIndex].WebFolderId=Ids[iIndex].Trim();
                }
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).SaveRoleMenu(SiteId, AssetCode, RoleId, RoleMenus);
                OAjaxOut.InfoMessage = "Cập nhật thành công chức năng phân quyền truy cập theo vị trí";
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}
